﻿

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
       
        var baiduBoundary = new BMap.Boundary();
 
      
        function getBoundsByCurrentIndex() {
            var name = document.getElementById("name").value;
            if(name == ""){
                alert("Name cannot be empty!");
                return ;
            }
            baiduBoundary.get(name, function (result) {
                if(result.boundaries.length == 0){
                    alert("Could not get city boundary for city '"+name+"', please check the input!");
                    return;
                }
                calcBound(result);
            });
        }

        function calcBound(obj){
            var data = obj.boundaries[0];
            var coordinates = data.split(";");
            var bound = {
                "right":-180,
                "left":180, 
                "top":-90,
                "bottom":90
            };
            var text = "POLYGON ((";
            for(var i = 0; i < coordinates.length; i++){
                var p = coordinates[i].split(",");
                var lon = parseFloat(p[0]);
                var lat = parseFloat(p[1]);
                if(bound.right < lon){
                    bound.right = lon;
                }
                if(bound.left > lon){
                    bound.left = lon;
                }
                if(bound.top < lat){
                    bound.top = lat;
                }
                if(bound.bottom > lat){
                    bound.bottom = lat;
                }
                text += lon+" "+lat;
                if(i != coordinates.length -1){
                    text+=",";
                }
            }
            text+="))";
            var boundbox = "POLYGON(("+bound.left+" "+bound.top+","+bound.right+" "+bound.top+","+bound.right+" "+bound.bottom+","+bound.left+" "+bound.bottom+","+bound.left+" "+bound.top+"))";
            
            $("#boundary").text(JSON.stringify(bound) +"  "+boundbox);
            $("#ploygonArea").text(text) ;
        }

    </script>
    <style type="text/css">
    </style>
</head>
<body>

    <div>
    <div><span>City Name:</span><input type="text" id="name" /><button onclick="getBoundsByCurrentIndex()">Get Boundary</button></div>
        <div><font color="red" size="20">Boundary:</font><span id="boundary"></span></div>
        <div><font color="red" size="20">Polygon Area:</font><span id="ploygonArea"></span></div>
    
        </textarea>
    </div>
</body>
</html>